import { NumberInputFormat } from '@app-cad/common/components/command-form/constants';
import { AngleMode, ArraySettings, FormData } from './types';

export const getDefaultArraySettings = () =>
  ({
    angleMode: 'distance',
    count: 4,
    angle: 360,
    singleAngle: 90,
  }) as ArraySettings;

export const getArraySettingsFromParams = (
  angleMode: AngleMode | undefined,
  count: number,
  angle: number,
  distance: number | undefined,
) => {
  const actualAngleMode = !angleMode
    ? // if no angleMode, it's the old API
      distance
      ? 'distance' // w/ `distance` param, the mode is `distance`
      : 'angle' // w/o `distance` param, the mode is `angle`
    : // otherwise, it's the new API, with explicit `angleMode`
      angleMode;

  return {
    angleMode: actualAngleMode,
    count: count ?? 4,
    angle: actualAngleMode === 'angle' ? angle : 360,
    // in old API, distance is the singleAngle; in new API, the dual-purpose angle is used regardless of the mode
    singleAngle: actualAngleMode === 'distance' ? distance || angle : 90,
  };
};

export const getArrayProperties = () => ({
  angleMode: {
    title: '模式',

    type: 'string',
    default: 'distance',
    oneOf: [
      {
        type: 'string',
        title: '间距',
        const: 'distance',
      },
      {
        type: 'string',
        title: '总角度',
        const: 'angle',
      },
    ],
  },
  count: {
    type: 'number',
    title: '阵列数量',
    default: 4,
    format: NumberInputFormat.Integer,
    minimum: 2,
  },
  angle: {
    type: 'number',
    title: '阵列总角度',
    default: 360,
    format: NumberInputFormat.Angle,
  },
  singleAngle: {
    type: 'number',
    title: '相邻角度间距',
    default: 90,
    format: NumberInputFormat.Angle,
  },
});

export const validateArraySettings = ({
  angleMode,
  count,
  angle,
  singleAngle,
}: ArraySettings) =>
  count != null && (angleMode === 'angle' ? angle > 0 : singleAngle > 0);

export const removeUnusedFieldForArray = (
  formData: FormData,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  schema: any,
  arrayPath: 'array1' | 'array2',
) => {
  const array = schema?.properties?.[arrayPath]?.properties;

  if (!array) {
    console.error(
      `Array ${arrayPath} not found in schema while removing unused fields`,
      schema,
    );
    return;
  }

  if (formData[arrayPath].angleMode === 'angle') {
    delete array.singleAngle;
  } else {
    delete array.angle;
  }
};
